import 'package:flutter/material.dart';
import 'package:ichineseaplus/presentation/assessments/mine_assessments_model.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

// ignore: must_be_immutable
class AssessmentsDataGrids extends StatelessWidget {
  AssessmentsDataGrids({
    Key? key,
    required this.assesssments,
    required this.isStudyRecord,
  }) : super(key: key);

  List<Assessment> assesssments;
  bool isStudyRecord = false;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  final DataGridController _dataGridController = DataGridController();

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Expanded(child: _buildAssessmentDataGrid()),
    ]);
  }

  SfDataGrid _buildAssessmentDataGrid() {
    return SfDataGrid(
      source: AssessmentDataGridSource(items: assesssments),
      controller: _dataGridController,
      checkboxColumnSettings:
          DataGridCheckboxColumnSettings(backgroundColor: Colors.blue[50]),
      allowSorting: true,
      allowTriStateSorting: true,
      allowSwiping: true,
      selectionMode: SelectionMode.multiple,
      navigationMode: GridNavigationMode.row,
      endSwipeActionsBuilder:
          (BuildContext context, DataGridRow row, int rowIndex) {
        return GestureDetector(
            onTap: () {
              // var assessmentId = row
              //     .getCells()
              //     .where((element) => element.columnName == 'Id')
              //     .first
              //     .value;

              // var status = row
              //     .getCells()
              //     .where((element) => element.columnName == 'Status')
              //     .first
              //     .value;
            },
            child: Container(
                color: Colors.redAccent,
                child: const Center(
                  child: Icon(Icons.delete),
                )));
      },
      columns: <GridColumn>[
        GridColumn(
            width: 320,
            columnName: 'Name',
            label: Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Name',
                overflow: TextOverflow.ellipsis,
                style: Get.textTheme.caption,
              ),
            )),
        GridColumn(
          columnName: 'Type',
          width: isWebOrDesktop ? 150 : 150,
          label: Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.all(8.0),
            child: Text(
              'Type',
              style: Get.textTheme.caption,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ),
        GridColumn(
          columnName: 'Status',
          width: isWebOrDesktop ? 160 : 160,
          label: Container(
            padding: const EdgeInsets.all(8.0),
            alignment: Alignment.centerLeft,
            child: Text(
              'Status',
              style: Get.textTheme.caption,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ),
        GridColumn(
          columnName: 'Text',
          width: isWebOrDesktop ? 180.0 : 180.0,
          label: Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.all(8.0),
            child: Text(
              'Text',
              style: Get.textTheme.caption,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ),
        GridColumn(
          columnName: 'Audio',
          width: isWebOrDesktop ? 180.0 : 180.0,
          label: Container(
              padding: const EdgeInsets.all(8.0),
              alignment: Alignment.center,
              child: Text(
                'Audio',
                style: Get.textTheme.caption,
                overflow: TextOverflow.ellipsis,
              )),
        ),
        GridColumn(
            columnName: 'StartDate',
            visible: isStudyRecord ? false : true,
            width: 180,
            label: Container(
                alignment: Alignment.centerRight,
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  'StartDate',
                  style: Get.textTheme.caption,
                  overflow: TextOverflow.ellipsis,
                ))),
          GridColumn(
            columnName: 'CorrectRate',
            visible: isStudyRecord ? true : false,
            width: 180,
            label: Container(
                alignment: Alignment.centerRight,
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  'CorrectRate',
                  style: Get.textTheme.caption,
                  overflow: TextOverflow.ellipsis,
                ))),
        GridColumn(
          columnName: 'SubmitDate',
          width: 180,
          label: Container(
              padding: const EdgeInsets.all(8.0),
              alignment: Alignment.centerRight,
              child: Text(
                'SubmitDate',
                style: Get.textTheme.caption,
                overflow: TextOverflow.ellipsis,
              )),
        ),
        GridColumn(
          columnName: 'Id',
          width: 10,
          visible: false,
          label: Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.all(8.0),
            child: Text(
              'Id',
              overflow: TextOverflow.ellipsis,
              style: Get.textTheme.caption,
            ),
          ),
        ),
      ],
    );
  }
}

class AssessmentDataGridSource extends DataGridSource {
  AssessmentDataGridSource({required List<Assessment> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                columnName: 'Name',
                value: dataGridRow.name,
              ),
              DataGridCell<String>(columnName: 'Type', value: dataGridRow.type),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.status?.toUpperCase()),
              DataGridCell<String>(
                  columnName: 'Text', value: dataGridRow.textType),
              DataGridCell<String>(
                  columnName: 'Audio', value: dataGridRow.audioType),
              DataGridCell<int>(
                  columnName: 'StartDate', value: dataGridRow.startTime),
              DataGridCell<int>(
                  columnName: 'CorrectReate', value: dataGridRow.correctRate),
              DataGridCell<int>(
                  columnName: 'SubmitDate', value: dataGridRow.submittedTime),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.id),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((dataGridCell) {
      if (dataGridCell.columnName == 'StartDate' ||
          dataGridCell.columnName == 'SubmitDate') {
        if (dataGridCell.value != null) {
          var date = DateTime.fromMillisecondsSinceEpoch(dataGridCell.value);
          return Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Text(
              DateFormat('yyyy-MM-dd').format(date),
              overflow: TextOverflow.ellipsis,
              style: Get.textTheme.caption,
            ),
          );
        } else {
          return Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: const Text(
                ' - ',
                overflow: TextOverflow.ellipsis,
              ));
        }
      } else if (dataGridCell.columnName == 'Status') {
        return Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Text(
            dataGridCell.value,
            overflow: TextOverflow.ellipsis,
            style: Get.textTheme.caption,
          ),
        );
      } else {
        return Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Text(
              dataGridCell.value.toString(),
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              style: Get.textTheme.caption,
            ));
      }
    }).toList());
  }
}
